//
//  YYTopicDetailViewController.swift
//  STMusic
//
//  Created by stoneobs on 17/5/10.
//  Copyright © 2017年 stoneobs. All rights reserved.
////**********************话题详情***************************

import UIKit

class YYTopicDetailViewController: UIViewController,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,UICollectionViewDelegate {

    var collectionView:UICollectionView?
    
    var topicModel:YYTopicModel! ;
    

    var allHederHeight:CGFloat = 0.0//整个collectionview 头部高度，悬停高度 50
    
    
    
    var header:UIView? //悬停View
    var currentTag:Int = 0//记录点击最新和最热的当前值
    var isSelectedPlayButton:Bool = false//是否点击过一键播放，点击一次之后就不允许添加到歌单了
    
    
    
    var segmentButton:STSegementButton?
    
    var playButton:STButton?//播放
    
    var sectionHeader:YYTopicHeaderView?
    
    var dataSouce:Array<YYTopicMusicModel> = [];
    
    var page:Int = 1;
    
    
    
    deinit {
        print("YYTopicDetailViewController 释放了")
    }
    init(topicModel:YYTopicModel) {
        
        super.init(nibName: nil, bundle: nil);
        self.topicModel = topicModel;
        
        
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = self.topicModel.title  ;
        self.sendTheTopicDetailRequest();
        self.sendTheTopicHotListRequest();
        self.configSubView();

        // Do any additional setup after loading the view.
    }

     // MARK:Config Subview
    func configSubView()  {
        
        self.automaticallyAdjustsScrollViewInsets = false;
        

        //collectionview
        let flowLaout = UICollectionViewFlowLayout.init();
        flowLaout.minimumLineSpacing = 5;
        flowLaout.minimumInteritemSpacing = 5;
        flowLaout.scrollDirection = .vertical;
        flowLaout.sectionInset = .init(top: 0, left: 10, bottom: 0, right: 10);
        self.collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT  - 64), collectionViewLayout: flowLaout);
        self.collectionView?.showsVerticalScrollIndicator = false;
        self.collectionView?.delegate = self;
        self.collectionView?.dataSource = self;
        self.collectionView?.alwaysBounceVertical = false;
        self.collectionView?.alwaysBounceHorizontal = false;
        self.collectionView?.register(YYTopicDetailCollectionViewCell.self, forCellWithReuseIdentifier: "item")
        self.collectionView?.register(YYTopicHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header");
        self.collectionView?.backgroundColor = YYThemeStyleManger.defultManger.gradualColor(frame: (self.collectionView?.bounds)!);
        self.view.addSubview(self.collectionView!);
        
        //悬停view,滑动到一定位置才显示
        weak var weakSelf = self;
        self.header = UIView.init(frame: .init(x: 0, y: 0, width: SCREEN_WIDTH, height: 50));
        self.header?.backgroundColor = YYThemeStyleManger.defultManger.gradualColor(frame: (self.header?.bounds)!);
        self.header?.isHidden = true;
        self.view.addSubview(self.header!);
        
        self.segmentButton  = STSegementButton.init(frame: .init(x: 20, y: 0, width: 160, height: 40), andTitle: ["最热","最新"], handle: { (but) in
            
            weakSelf?.segementAction(tag: (but?.tag)!);
            weakSelf?.currentTag = (but?.tag)!;
            weakSelf?.sectionHeader?.segmentButton?.cureentIndex = (but?.tag)!;
        });
        self.segmentButton?.butTitleColor = ThirdTextColor;
        self.segmentButton?.lineColor = .clear;
        self.segmentButton?.backgroundColor = .clear;
        self.segmentButton?.butTitleSelectedColor = .white;
        self.segmentButton?.lineSelectedColor = .white;
        self.segmentButton?.autoMoveWithClic = true;
        self.segmentButton?.isShowSpringAnimation = false;
        self.segmentButton?.centerY = (self.header?.height)! / 2;
        self.header?.addSubview(self.segmentButton!);
        
        self.playButton = STButton.init(frame: .init(x: SCREEN_WIDTH - 100 , y: 0, width: 90, height: 40), title: "一键播放", titleColor: .white, titleFont: 15, cornerRadius: 0, backgroundColor: .clear, backgroundImage: nil, image: nil);
        self.playButton?.centerY = (self.header?.height)! / 2;
        self.playButton?.contentHorizontalAlignment = .right;
        self.playButton?.clicAction = {but in
            weakSelf?.isSelectedPlayButton = true;
            weakSelf?.playAllAction()
        }
        self.header?.addSubview(self.playButton!);
        
        
        self.collectionView?.mj_header = MJChiBaoZiHeader.init(refreshingBlock: {
            weakSelf?.dataSouce = [];
            weakSelf?.page = 1;
            weakSelf?.sendTheTopicHotListRequest();
        });
        
        self.collectionView?.mj_footer = MJChiBaoZiFooter.init(refreshingBlock: { 
            weakSelf?.page = (weakSelf?.page)! + 1;
            weakSelf?.sendTheTopicHotListRequest();
            
        });
        
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1;
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataSouce.count;
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let witdh = SCREEN_WIDTH / 2 - 10 - 2.5;
        return CGSize.init(width: witdh, height: witdh);
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        let head:YYTopicHeaderView = YYTopicHeaderView.init(frame: SCREEN_FRAME);
        head.model = self.topicModel;
        self.allHederHeight = head.headerViewHeight;
        return CGSize.init(width: SCREEN_WIDTH, height: head.headerViewHeight);
    }
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let head:YYTopicHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header", for: indexPath) as! YYTopicHeaderView;
        head.model = self.topicModel;
        head.segmentButton?.cureentIndex = self.currentTag;
        weak var weakSelf = self;
        head.segmentButton?.action = { but in
        
            weakSelf?.segmentButton?.cureentIndex = (but?.tag)!;
            weakSelf?.segementAction(tag: (but?.tag)!);
            weakSelf?.currentTag = (but?.tag)!;
            
        }
        head.playButton?.clicAction = { but in
        
            weakSelf?.isSelectedPlayButton = true;
            weakSelf?.playAllAction();
            
        }
        head.userView?.iconButton?.clicAction = {[weak head] but in
        
            weakSelf?.iconAction(model: (head?.model?.user)!)
        }
        sectionHeader = head;
        return head;
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:YYTopicDetailCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "item", for: indexPath) as! YYTopicDetailCollectionViewCell;
        cell.model = self.dataSouce[indexPath.row];
        return cell;
        
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.dataSouce[indexPath.row];
        let vc = YYPlayDetailViewController.init(musicID: (self.dataSouce[indexPath.row].works?.id)!)
        vc.backgroundImageUrl = model.works?.cover_photo;
        vc.type = "1";
        self.navigationController?.pushViewController(vc, animated: true);
    }
    //MARK:UIScrollViewDelegate
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        //print("移动了\(self.collectionView?.contentOffset.y)");
        if (self.allHederHeight - 50 ) <= (self.collectionView?.contentOffset.y)! {
            self.header?.isHidden = false;
            sectionHeader?.header?.isHidden = true;
            
        }else{
            self.header?.isHidden = true;
            sectionHeader?.header?.isHidden = false;
        }
        if (self.collectionView?.contentOffset.y)! >= (self.allHederHeight + 50 )  {
            let cha = (self.collectionView?.contentOffset.y)! - (self.allHederHeight + 50 );
            let max = 600 - (self.collectionView?.contentOffset.y)!;
            if max > 0 {
                var alphy = cha / max;
                alphy = alphy > 0.7 ? 0.7:alphy;
                self.header?.backgroundColor = self.header?.backgroundColor?.withAlphaComponent(1 - alphy)
            }else{
                self.header?.backgroundColor = self.header?.backgroundColor?.withAlphaComponent(0.3)
            }

        }else{
            self.header?.backgroundColor = YYThemeStyleManger.defultManger.gradualColor(frame: (self.header?.bounds)!);
        }
    }
    //获取topic详情
    func sendTheTopicDetailRequest() -> Void {
        //https://api.suiyueyule.com/1.0.2/topic/detail/986?lang=utf8
        //"https://api.suiyueyule.com/1.0.2/topic/detail/\(self.topicID!)?lang=utf8"
        let url = "https://api.suiyueyule.com/1.0.2/topic/detail/\((self.topicModel.id)!)?lang=utf8";
        YYSuiYueNetWorkManger.defultManger.getNetwork(urlString: url, dic: [:], successHandle: { (json) in
            
            if let mydic = json["data"] as? NSDictionary{
                if let topicDic = mydic["topic"] as? NSDictionary{
                
                    let topModel = YYTopicModel.mj_object(withKeyValues: topicDic);
                    
                    self.topicModel = topModel;
                    self.collectionView?.reloadData();
                }
            }
    
        }) { (des) in
            
        }
    }

    //获取最热列表
    func sendTheTopicHotListRequest() -> Void {

        let url = "https://api.suiyueyule.com/1.0.2/topic/list/hot?lang=utf8&page=\(self.page)&r=&topic_id=\((self.topicModel.id)!)";
        YYSuiYueNetWorkManger.defultManger.getNetwork(urlString: url, dic: [:], successHandle: { (json) in
            
            self.collectionView?.mj_footer?.endRefreshing();
            self.collectionView?.mj_header?.endRefreshing();
            if let mydic = json["data"] as? NSDictionary{
                if let array:Array<Dictionary<String,Any>> = mydic["list"] as? Array{
                    
                        for dic in array {
                    
                        let model:YYTopicMusicModel = YYTopicMusicModel.mj_object(withKeyValues: dic);
                        self.dataSouce.append(model);
                        
                    }
                    if array.count == 0{
                        self.collectionView?.mj_footer.endRefreshingWithNoMoreData();
                    }
                    self.collectionView?.reloadData();
                }
            }
            
            if self.dataSouce.count < 6{
                self.collectionView?.mj_footer = nil;
            }

            
        }) { (des) in
            
            self.collectionView?.mj_footer.endRefreshing();
            self.collectionView?.mj_header.endRefreshing();
        }
    }
    //获取最新列表
    func sendTheTopicNewListRequest() -> Void {

        let url = "https://api.suiyueyule.com/1.0.2/topic/list/new?lang=utf8&page=\(self.page)&r=&topic_id=\((self.topicModel.id)!)";
        YYSuiYueNetWorkManger.defultManger.getNetwork(urlString: url, dic: [:], successHandle: { (json) in
            
            self.collectionView?.mj_footer?.endRefreshing();
            self.collectionView?.mj_header?.endRefreshing();
            if let mydic = json["data"] as? NSDictionary{
                if let array:Array<Dictionary<String,Any>> = mydic["list"] as? Array{
                    
                    for dic in array {
                        
                        let model:YYTopicMusicModel = YYTopicMusicModel.mj_object(withKeyValues: dic);
                        self.dataSouce.append(model);
                        
                    }
                    if array.count == 0{
                        self.collectionView?.mj_footer.endRefreshingWithNoMoreData();
                    }
                    self.collectionView?.reloadData();
                }
            }
            if self.dataSouce.count < 6{
                self.collectionView?.mj_footer = nil;
            }
            
        }) { (des) in
            
            self.collectionView?.mj_footer.endRefreshing();
            self.collectionView?.mj_header.endRefreshing();
        }
    }
        // MARK:Action Method
    //最新最热点击事件
    func segementAction(tag:Int)  {
        switch tag {
        case 0:
            //最热
            self.dataSouce = [];
            self.page = 1;
            self.sendTheTopicHotListRequest()
            break
           
        case 1:
            //最新
            self.dataSouce = [];
            self.page = 1;
            self.sendTheTopicNewListRequest();
            break
        default: break
            
        }
    }
    //头像
    func iconAction(model:YYuserModel) {
        print("icon action")
    }
    //一键播放
    func playAllAction()  {
        
        print("这个接口无法获取，批量获取资源是一个非常危险的操作，容易暴露和流失资源，所以底层写一个请求，批量传入id，这里所有的资源绑定了authKey，一般一天会更新，所以底层数据库，YYMusicModel ,字段type碎月，酷狗等，id,path。根据id 来判断是否有缓存")
    }

}
